package com.my.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.my.entity.WecomMessageSeq;
import com.my.mapper.WecomMessageSeqMapper;
import com.my.service.WecomMessageSeqService;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @author sjx
 * @date 2025/2/24 16:52
 */
@Service
public class WecomMessageSeqServiceImpl extends ServiceImpl<WecomMessageSeqMapper, WecomMessageSeq> implements WecomMessageSeqService {
    @Override
    public Long getSeq() {
        long seq = 0L;
        Optional<WecomMessageSeq> wecomMessageSeqOpt = this.lambdaQuery()
                .eq(WecomMessageSeq::getType,1)
                .oneOpt();
        if(!wecomMessageSeqOpt.isPresent()){
            WecomMessageSeq addInfo = new WecomMessageSeq();
            addInfo.setSeq(seq);
            addInfo.setType(1);
            this.save(addInfo);
        } else {
            WecomMessageSeq wecomMessageSeq = wecomMessageSeqOpt.get();
            seq = wecomMessageSeq.getSeq();
        }
        return seq + 1;
    }

    @Override
    public void upSeq(Long seqVal) {
        Optional<WecomMessageSeq> wecomMessageSeqOpt = this.lambdaQuery()
                .eq(WecomMessageSeq::getType,1)
                .oneOpt();
        if(!wecomMessageSeqOpt.isPresent()){
            throw new RuntimeException("序号不存在");
        }

        WecomMessageSeq wecomMessageSeq = wecomMessageSeqOpt.get();

        boolean flag = Boolean.FALSE;
        while(!flag){
            flag = this.lambdaUpdate()
                    .set(WecomMessageSeq::getSeq,seqVal)
                    .eq(WecomMessageSeq::getId,wecomMessageSeq.getId())
                    .eq(WecomMessageSeq::getSeq,wecomMessageSeq.getSeq())
                    .update();
        }

    }
}
